package com.backend.api.security.service;

import com.common.model.Admin;
import com.common.model.Menu;
import com.backend.api.security.entity.SelfAdminEntity;
import com.common.service.AdminService;
import com.common.service.MenuService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;

/**
 * SpringSecurity用户的业务实现
 */
@Service
public class SelfUserDetailsService implements UserDetailsService {

    private AdminService adminService;

    private MenuService menuService;

    /**
     * 查询用户信息
     */
    @Override
    public SelfAdminEntity loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        Admin admin = adminService.findByUsername(username);
        if (admin != null) {
            // 组装参数
            SelfAdminEntity selfAdminEntity = new SelfAdminEntity();
            BeanUtils.copyProperties(admin, selfAdminEntity);
            //加载权限
            List<Menu> menus = menuService.findByAdminId(admin.getAdminId());
            List<GrantedAuthority> list = new LinkedList<>();
            for (Menu menu : menus) {
                list.add(new SimpleGrantedAuthority(menu.getRequestPerm()));
            }
            selfAdminEntity.setAuthorities(list);
            return selfAdminEntity;
        }
        return null;
    }

    @Autowired
    public void setAdminService(AdminService adminService) {
        this.adminService = adminService;
    }

    @Autowired
    public void setMenuService(MenuService menuService) {
        this.menuService = menuService;
    }
}